package com.situ.stl.fore;

import com.situ.stl.entity.Member;
import com.situ.stl.entity.Reserve;
import com.situ.stl.entity.Result;
import com.situ.stl.service.MemberService;
import com.situ.stl.service.ReserveService;
import com.situ.stl.util.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/** 
 * Controller层 - 预约
 */
@RestController("/foreReserveController")
@RequestMapping( value = "/fore/reserve")
@Slf4j
public class ReserveController {

    /** 
     */
    @Autowired 
    private ReserveService reserveService;
    @Autowired
    private MemberService memberService;

    /** 
     * add
     */
    @PostMapping 
    public Result add(@RequestBody Reserve reserve, HttpServletRequest request) {
        // 读取请求头中的Token
        String token = request.getHeader("token");

        // 当前登录用户
        Member member = null;
        // 有Token, 解析
        if ( StringUtils.hasText(token)) {
            // 尝试解析
            try {
                Claims claims = JWTUtil.parseJWT(token);
                String phone = claims.getSubject();
                member = memberService.getByPhone(phone);
            } catch (Exception e) {
                log.info("无效的token");
            }
        }

        try {
            if (member != null) {
                reserve.setMemberId(member.getId());
            } else {
                throw new Exception("会员未登录！");
            }
            reserveService.add(reserve);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /** 
     * remove
     */
    @DeleteMapping 
    public Result remove( Integer id) {

        try {
            reserveService.remove(id);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }

    /** 
     * edit
     */
    @PutMapping 
    public Result edit( @RequestBody Reserve reserve) {
        try {
            reserveService.edit(reserve);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
}